package com.example.rbacmanage.util;

import org.apache.commons.codec.binary.Base64;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;

public class FileUtils {
    public static File base64ToFile(String base64, String filePath) {
        File file = new File(filePath);
        byte[] buffer;
        try {
            Base64 base64Decoder = new Base64();
            buffer = base64Decoder.decode(base64);
            FileOutputStream out = new FileOutputStream(filePath);
            out.write(buffer);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 创建基本日期文件夹目录
     * @param filePath
     * @return
     */
    public static String createBaseDateFileMkdir(String filePath) {
        LocalDate currentDate = LocalDate.now();
        String dateDir = filePath + String.format("%s/%s/%s",currentDate.getYear(),currentDate.getMonthValue(),currentDate.getDayOfMonth());
        Path dirPath = Paths.get(dateDir);
        if (!Files.exists(dirPath)){
            try {
                Files.createDirectories(dirPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return dateDir;
    }

    public static MultipartFile convert(String base64String, String originalFilename){
        try{
            // 解码Base64字符串为字节数组
            byte[] decodedBytes = java.util.Base64.getDecoder().decode(base64String);

            // 创建临时文件
            Path tempFile = Files.createTempFile("upload-", ".jpeg");

            // 将字节数组写入临时文件
            Files.write(tempFile, decodedBytes);

            // 读取临时文件内容并封装为MockMultipartFile
            File file = tempFile.toFile();
            file.deleteOnExit();
            return new MockMultipartFile(
                    "file",
                    originalFilename,
                    null,
                    new ByteArrayInputStream(decodedBytes)
            );
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
